/**
 * 图⽚压缩，默认同⽐例压缩
 * @param fileObj
 * 图⽚对象
 * 回调函数有⼀个参数，base64的字符串数据
 * @param maxSize  默认 500K
 * 对多⼤的图⽚进⾏压缩 file.size
 * @param picQuality  默认0.7
 * 压缩图⽚的质量 0~1
 * @returns {Promise}
 */
import { Message } from "element-ui"
export function compress(fileObj, maxSize = 500, picQuality = 0.6) {
  return new Promise((resolve, reject) => {
    const isJPG = (
      fileObj.type === "image/jpeg" ||
      fileObj.type === "image/png" ||
      fileObj.type === "image/bmp"
    )
    if (fileObj.size && ((fileObj.size / 1024) > maxSize) && isJPG) {
      try {
        // ⼤于1MB的图⽚进⾏压缩
        const image = new Image()
        image.src = URL.createObjectURL(fileObj)
        image.onload = function() {
          const that = this
          // 默认按⽐例压缩
          let w = that.width
          let h = that.height
          const scale = w / h
          w = fileObj.width || w
          h = fileObj.height || (w / scale)
          let quality = picQuality // 默认图⽚质量为0.7
          // ⽣成canvas
          const canvas = document.createElement("canvas")
          const ctx = canvas.getContext("2d")
          // 创建属性节点
          const anw = document.createAttribute("width")
          anw.nodeValue = w
          const anh = document.createAttribute("height")
          anh.nodeValue = h
          canvas.setAttributeNode(anw)
          canvas.setAttributeNode(anh)
          ctx.drawImage(that, 0, 0, w, h)
          // 图像质量
          if (fileObj.quality && fileObj.quality <= 1 && fileObj.quality > 0) {
            quality = fileObj.quality
          }
          // quality值越⼩，所绘制出的图像越模糊
          const data = canvas.toDataURL(fileObj.type, quality)
          // 压缩完成执⾏回调
          const newFile = convertBase64UrlToBlob(data)
          newFile.name = fileObj.name || "未知.png"
          resolve(newFile)
        }
      } catch (e) {
        Message.warning("图⽚压缩失败~")
        resolve(fileObj)
      }
    } else {
      resolve(fileObj)
    }
  })
}
export function convertBase64UrlToBlob(urlData) {
  const bytes = window.atob(urlData.split(",")[1]) // 去掉url的头，并转换为byte
  // 处理异常,将ascii码⼩于0的转换为⼤于0
  const ab = new ArrayBuffer(bytes.length)
  const ia = new Uint8Array(ab)
  for (let i = 0; i < bytes.length; i++) {
    ia[i] = bytes.charCodeAt(i)
  }
  return new Blob([ab], { type: "image/png" })
}